package org.tloss.web.editor.message.editors;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.tloss.web.editor.model.Field;
import org.tloss.web.editor.model.Message;
import org.tloss.web.editor.utils.Constants;

public class MessageElement implements IWorkbenchAdapter, IAdaptable {
	MessageModel messageModel;
	IResourceChangeListener listener;

	public MessageElement(MessageModel messageModel,
			IResourceChangeListener listener) {
		this.messageModel = messageModel;
		this.listener = listener;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Object getAdapter(Class adapter) {
		if (adapter == IWorkbenchAdapter.class)
			return this;

		return null;
	}

	@Override
	public Object[] getChildren(Object o) {

		Message message = messageModel.getMessage();
		if (message != null) {
			List<Field> fields = message.getFields();
			if (fields != null && fields.size() > 0) {
				List<FieldElement> elements = new ArrayList<FieldElement>();
				FieldElement element;
				for (int i = 0; i < fields.size(); i++) {
					element = new FieldElement();
					element.setField(fields.get(i));
					element.setListener(listener);
					elements.add(element);
				}
				if (elements.size() > 0) {
					return elements.toArray();
				}
			}
		}
		return Constants.EMPTY_ARRAY;
	}

	@Override
	public ImageDescriptor getImageDescriptor(Object object) {

		return null;
	}

	@Override
	public String getLabel(Object o) {
		return o == null ? "" : o.toString();
	}

	@Override
	public Object getParent(Object o) {

		return null;
	}

}
